﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using JLL.China.Application;
using JLL.China.Infrastructure.Services;
using JLL.China.Web.Areas.Portal.Models;
using JLL.China.Web.Libraries;
namespace JLL.China.Web.Areas.Portal.Controllers
{
    public class SideContentController : Controller
    {

        protected int defaultPageSize = Int32.Parse(WebConfigurationManager.AppSettings["page_size_default"]);

        public SideContentController()
        {
            ViewData["now_controller"] = "Portal/SideContent/";
            ViewData["Title"] = "Side Content";
        }
        //
        // GET: /Portal/SideContent/
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">id = 1 dynamic banner, 2 static banner,0 both</param>
        /// <returns></returns>
        public ActionResult Index(int? id, int? page)
        {

            if (Session["page_size_default"] != null)
            {
                ViewData["per-page"] = Session["page_size_default"].ToString();
                defaultPageSize = Int32.Parse(Session["page_size_default"].ToString());
            }
            else
            {
                ViewData["per-page"] = defaultPageSize;
            }
            int currentPageIndex = page.HasValue ? page.Value : 1;
            //Strore Session
            Session["heading"] = "Manage News ";
            Session["pageindex"] = currentPageIndex;



            var model = new Models.BannerModel();
            if (id != null)
            {
                switch (id)
                {
                    case 1://dynamic
                        var dynamicContent = BannerService.GetAllMainSideContentsInGroup(1);
                        ViewData["dynamiccount"] = dynamicContent.Count;
                        model.Banners = dynamicContent;
                        ViewData["typebanner"] = "dynamic";
                        Session["id"] = "dynamic";
                        break;
                    case 2: //static
                        var staticContent = BannerService.GetAllMainSideContentsInGroup(2);
                        ViewData["staticcount"] = staticContent.Count;
                        model.Banners = staticContent;
                        ViewData["typebanner"] = "static";
                        Session["id"] = "static";
                        break;
                }
            }
            else
            {
                model.Banners = BannerService.GetDistinctSideContent();
                ViewData["typebanner"] = "dynamic";
                Session["id"] = "dynamic";
            }


            return View(model.Banners.ToPagedList(currentPageIndex, defaultPageSize));
        }

        public ActionResult BulkProcess(string status, IEnumerable<decimal> selected)
        {
            try
            {
                if (!checkUserLogin())
                {
                    return RedirectToAction("LogIn", "Home", new { area = "" });
                }
                string arr_id = "0";
                foreach (var key in selected)
                {
                    arr_id += "," + key.ToString();
                }
                if (status.Equals("active"))
                {
                    //   NewsService.ChangeEventStatus(arr_id, true);
                    BannerService.ChangeGroupStatus(arr_id, true);
                }

                if (status.Equals("inactive"))
                {
                    //EventService.ChangeEventStatus(arr_id, false);
                    BannerService.ChangeGroupStatus(arr_id, false);
                }

                if (status.Equals("remove"))
                {
                    BannerService.RemoveSelectedGroup(arr_id);
                }
                ShowMessage("Records updated successfully.", "Success");
            }
            catch (Exception)
            {
                ShowMessage("Records updated unsuccessfully.", "Error");
            }


            // return RedirectToAction("Index/1?page=" + Session["pageindex"].ToString());
            return RedirectToAction("Index/" + (Session["id"].ToString().Equals("dynamic") ? 1 : 2), new { page = Session["pageindex"] });
        }


        void GetBannerCount()
        {
            ViewData["staticcount"] = BannerService.GetAllMainSideContentsInGroup(2).Count;
            ViewData["dynamiccount"] = BannerService.GetAllMainSideContentsInGroup(1).Count;
        }

        void GetStaticContentCount()
        {
            ViewData["staticcount"] = BannerService.GetAllMainSideContentsInGroup(2).Count;
        }
        void GetDynamicContentCount()
        {
            ViewData["dynamiccount"] = BannerService.GetAllMainSideContentsInGroup(1).Count;
        }

        public bool checkUserLogin()
        {
            var loginAcc = this.Session[Constants.Session_User] as Model.Admin;
            if (loginAcc == null)
            {
                return false;
            }
            return true;
        }
        private string UploadFile(HttpPostedFileBase file)
        {
            try
            {
                if (file == null)
                {
                    return null;
                }

                string mediaRootPath = Server.MapPath("~/Media/Banner/SideContent");


                if (!Directory.Exists(mediaRootPath))
                {
                    Directory.CreateDirectory(mediaRootPath);
                }
              //  string name = System.IO.Path.GetFileName(file.FileName);
                string ext = System.IO.Path.GetExtension(file.FileName);
               
                string filenameguid = Guid.NewGuid().ToString();
                string name = filenameguid + ext;
                string fullFilePath = mediaRootPath + "\\" + name;
                ResizeStream(new Size(356, 283), file.InputStream, fullFilePath);

                //file.SaveAs(fullFilePath);

                return name;

            }
            catch (Exception)
            {

                return null;
            }

        }

        public void ResizeStream(Size imageSize, Stream filePath, string outputPath)
        {
            var image = Image.FromStream(filePath);

            int newWidth, newHeight;


            newWidth = imageSize.Width;
            newHeight = imageSize.Height;


            var thumbnailBitmap = new Bitmap(newWidth, newHeight);

            var thumbnailGraph = Graphics.FromImage(thumbnailBitmap);
            thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
            thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
            thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

            var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
            thumbnailGraph.DrawImage(image, imageRectangle);

            thumbnailBitmap.Save(outputPath, image.RawFormat);
            thumbnailGraph.Dispose();
            thumbnailBitmap.Dispose();
            image.Dispose();
        }





        #region  action for Dynamic side
        /// <summary>
        /// create, update main banner
        /// </summary>
        /// <param name="name"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CreateMainDynamicBanner(Models.BannerModel model)
        {
            ViewData["typebanner"] = "dynamic";
            decimal res = -1;
            decimal parentIdR = 0;
            if (model.Banner_Local.Banner_ID != null)//for update
            {
                res = BannerService.UpdateParentBanner(model.Banner_Local);
                parentIdR = (decimal)model.Banner_Local.Banner_ID;
            }
            else //for insert
            {
                model.Banner_Local.LanguageFID = 1;
                model.Banner_Local.BannerGroupFID = 3;
                model.Banner_Local.Type = "dynamic";
                res = BannerService.CreateBanner(model.Banner_Local);
                //update parent id for this
                var dynamic = BannerService.FindByID_LanguageFid(res, 1);

                dynamic.ParentID = res;
                BannerService.UpdateBanner(dynamic);

                ShowMessage("Created successfully.", "Success");
                return RedirectToAction("CreateDynamic", new { parentId = res });
            }
            if (res != -1)
            {

                ShowMessage("Saved successfully.", "Success");
                return RedirectToAction("CreateDynamic", new { parentId = parentIdR });
            }
            else
            {
                ShowMessage("Record updated unsuccessfully.", "Error");
                return RedirectToAction("Index" + (Session["id"].ToString().Equals("dynamic") ? 1 : 2), new { page = Session["pageindex"] });
            }



        }

        [Authorize]
        public ActionResult CreateDynamic(decimal? id, decimal? parentId)
        {
            ViewData["typebanner"] = "dynamic";
            ViewData["now_controller"] = "Portal/SideContent/";
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            try
            {
                GetDynamicContentCount();
                var model = new BannerModel();
                //model.Banner_Local is mainbanner
                //model.Banner is subbanner
                if (id == null && parentId == null)//insert new group
                {
                    return View(model);
                }

                if (parentId != null) //for insert banner to group banner
                {
                    model.Banner_Local = BannerService.GetMainSideContent(1, parentId);
                    model.Banners = BannerService.GetAllSideContentInGroup(1, parentId); /*side banner*/
                }

                if (id != null)
                {
                    //for edit
                    if (id != parentId) //must not be a main group banner
                    {
                        model.Banner = BannerService.FindByID_LanguageFid(id, 1);

                        model.Banner.ParentID = parentId;
                    }

                }

                return View(model);

            }
            catch (Exception)
            {

                return RedirectToAction("Index/1", new { page = Session["pageindex"] });
            }



        }
        //
        // POST: /Portal/SideContent/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateDynamic(BannerModel model, HttpPostedFileBase file)
        {
            try
            {
                ViewData["typebanner"] = "dynamic";
                if (!checkUserLogin())
                {
                    RedirectToAction("LogIn", "Home", new { area = "" });
                }
                decimal res = -1;//insert/update unsuccessfully

                model.Banner.BannerGroupFID = 3;//side content banner
                model.Banner.Type = "dynamic";
                model.Banner.LanguageFID = 1;
                //model.Banner_Local.BannerGroupFID = 3;//side content banner
                //model.Banner_Local.Type = "dynamic";
                //model.Banner_Local.LanguageFID = 1;


                if (model.Banner.Banner_ID == null)
                //for insert banner to group banner
                {
                    model.Banner.ParentID = model.Banner_Local.ParentID;
                    model.Banner.BannerUrl = UploadFile(file);
                    res = BannerService.CreateBanner(model.Banner); //insert 
                }
                else
                {

                    model.Banner.BannerUrl = UploadFile(file);
                    res = BannerService.UpdateBanner(model.Banner);
                    res = BannerService.UpdateBanner(model.Banner_Local);

                }

                if (res != -1)
                {

                    ShowMessage("Records updated successfully.", "Success");
                }
                else
                {
                    ShowMessage("Records updated unsuccessfully.", "Error");
                }

                return RedirectToAction("CreateDynamic", new { parentId = model.Banner_Local.ParentID });
            }
            catch
            {
                return RedirectToAction("Index", new { page = Session["pageindex"] });
            }
        }



        public ActionResult DeleteDynamicSubBanner(decimal? id, decimal? parentid)
        {
            if (id != null)
            {
                if (parentid != null)
                {
                    BannerService.DeleteStaticDynamic(parentid);
                }
                else
                {
                    BannerService.DeleteBanner(id);
                }
            }
            else
            {
                if (parentid != null)
                {
                    BannerService.DeleteStaticDynamic(parentid);
                }
            }
            ShowMessage("Deleted successfully.", "Success");
            return RedirectToAction("CreateDynamic", new { parentId = parentid });

        }
        #endregion

        void ShowMessage(string msg, string type)
        {
            Session["message"] = msg;
            Session["messageType"] = type;
        }
        public ActionResult DeleteFile(string filename, decimal? id)
        {
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            System.IO.File.Delete(filename);
            //            Session["message"] = "Delete file successfully.";
            //            Session["messageType"] = "Success";
            ShowMessage("Delete file successfully.", "Success");
            return RedirectToAction("CreateStatic", new { id = id });
        }

        #region "Action For Static"
        /* [HttpPost]
        public ActionResult CreateStatic(Models.BannerModel model)
        {
            ViewData["typebanner"] = "static";
            GetStaticContentCount();
            decimal res = -1;
            decimal parentIdR = 0;
            if (model.Banner_Local.Banner_ID != null)//for update
            {
                res = BannerService.UpdateParentBanner(model.Banner_Local);
                parentIdR = (decimal)model.Banner_Local.Banner_ID;
            }
            else //for insert
            {
                model.Banner_Local.LanguageFID = 1;
                model.Banner_Local.BannerGroupFID = 3;
                model.Banner_Local.Type = "dynamic";
                res = BannerService.CreateBanner(model.Banner_Local);
                //update parent id for this
                var dynamic = BannerService.FindByID_LanguageFid(res, 1);

                dynamic.ParentID = res;
                BannerService.UpdateBanner(dynamic);

                ShowMessage("Created successfully.", "Success");
                return RedirectToAction("CreateDynamic", new { parentId = res });
            }
            if (res != -1)
            {

                ShowMessage("Saved successfully.", "Success");
                return RedirectToAction("CreateDynamic", new { parentId = parentIdR });
            }
            else
            {
                ShowMessage("Record updated unsuccessfully.", "Error");
                return RedirectToAction("Index" + (Session["id"].ToString().Equals("dynamic") ? 1 : 2), new { page = Session["pageindex"] });
            }



        }
        */

        [Authorize]
        public ActionResult CreateStatic(int? id)
        {
            ViewData["typebanner"] = "static";

            ViewData["now_controller"] = "Portal/SideContent/";
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            GetBannerCount();
            try
            {
                //GetStaticContentCount();

                List<FileInfo> files = FromFolder("~/Media/Banner/MediaFiles");
                ViewData["files"] = files;
                var model = new BannerModel();
                //model.Banner_Local is mainbanner
                //model.Banner is subbanner
                if (id == null)//insert new group
                {
                    return View(model);
                }

                if (id != null) //for insert banner to group banner
                {
                    Session["id"] = id;
                    model.Banner_Local = BannerService.FindByID_LanguageFid(id, 2);
                    model.Banner = BannerService.FindByID_LanguageFid(id, 1); /*side banner*/
                }


                return View(model);
            }
            catch
            {
                ShowMessage("Record updated unsuccessfully.", "Error");
                return RedirectToAction("Index/2", new { page = Session["pageindex"] });
            }

        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateStatic(BannerModel model)
        {
            try
            {
                ViewData["typebanner"] = "static";
                GetBannerCount();
                // GetStaticContentCount();
                if (!checkUserLogin())
                {
                    return RedirectToAction("LogIn", "Home", new { area = "" });
                }
                decimal res = -1;//insert/update unsuccessfully

                model.Banner.BannerGroupFID = 3;//side content banner
                model.Banner.Type = "static";
                model.Banner.LanguageFID = 1;
                model.Banner_Local.BannerGroupFID = 3;//side content banner
                model.Banner_Local.Type = "static";
                model.Banner_Local.LanguageFID = 1;
                model.Banner_Local.Title = model.Banner.Title;
                if (model.Banner.Banner_ID == null)
                //for insert static banner
                {
                    //model.Banner.ParentID = model.Banner_Local.ParentID;
                    //model.Banner.BannerUrl = UploadFile(file);
                    res = BannerService.CreateBanner(model.Banner, model.Banner_Local); //insert 
                    var _static = BannerService.FindByID_LanguageFid(res, 1);
                    _static.ParentID = res;
                    _static.Sequence = (int)_static.Banner_ID.Value;
                    BannerService.UpdateBanner(_static);

                    _static = BannerService.FindByID_LanguageFid(res, 2);
                    _static.ParentID = res;
                    _static.Sequence = (int)_static.Banner_ID.Value;
                    BannerService.UpdateBanner(_static);

                }
                else
                {

                    //model.Banner.BannerUrl = UploadFile(file);
                    //res = BannerService.UpdateBanner(model.Banner);

                    res = BannerService.UpdateBanner(model.Banner);
                    res = BannerService.UpdateBanner(model.Banner_Local);

                }

                if (res != -1)
                {

                    ShowMessage("Records updated successfully.", "Success");
                }
                else
                {
                    ShowMessage("Records updated unsuccessfully.", "Error");
                }

                return RedirectToAction("Index/2", new { page = Session["pageindex"] });
            }
            catch
            {
                return RedirectToAction("Index/2", new { page = Session["pageindex"] });
            }
        }


        public ActionResult UploadFiles(HttpPostedFileBase FileData, FormCollection forms)
        {
            try
            {
                if (FileData == null)
                {
                    return null;
                }

                string mediaRootPath = Server.MapPath("~/Media/Banner/MediaFiles");



                if (!Directory.Exists(mediaRootPath))
                {
                    Directory.CreateDirectory(mediaRootPath);
                }
                string ext = System.IO.Path.GetExtension(FileData.FileName);
                string filenameguid = Guid.NewGuid().ToString();
                // string name = System.IO.Path.GetFileName(FileData.FileName);
                string name = filenameguid + ext;
                string fullFilePath = mediaRootPath + "\\" + name;
                FileData.SaveAs(fullFilePath);

                return RedirectToAction("CreateStaticBanner", new { id = Session["id"] ?? null });

            }
            catch (Exception)
            {

                return RedirectToAction("Index/2");
            }


        }
        List<FileInfo> FromFolder(string folderName)
        {
            string path = Server.MapPath(folderName);
            //string SourecPath = HttpContext.Request.MapPath(path);
            if (!Directory.Exists(path))
            {
                return null;
            }
            DirectoryInfo sourcedinfo = new DirectoryInfo(path);

            var files = sourcedinfo.GetFiles();
            List<FileInfo> fs = new List<FileInfo>();
            foreach (var fileInfo in files)
            {
                //                if (fileInfo.Name.StartsWith(sufix))
                //                {
                fs.Add(fileInfo);
                //                }

            }
            return fs;
        }
        #endregion



        public ActionResult Delete(decimal? id, decimal? parentid, string dynamicStatic)
        {
            if (id != null)
            {
                if (parentid != null)
                {
                    BannerService.DeleteStaticDynamic(parentid);
                }
                else
                {
                    BannerService.DeleteBanner(id);
                }
            }
            else
            {
                if (parentid != null)
                {
                    BannerService.DeleteStaticDynamic(parentid);
                }
            }
            ShowMessage("Deleted successfully.", "Success");
            if(!string.IsNullOrEmpty(dynamicStatic))
                return RedirectToAction("Index/" + (dynamicStatic.Equals("dynamic") ? 1 : 2), new { page = Session["pageindex"] });

            return RedirectToAction("Index/1" , new { page = Session["pageindex"] });
            
        }
        public ActionResult ChangeStatus(decimal? id, decimal? parentid, string dynamicStatic)
        {
            if (id != null)
            {
                if (parentid != null)
                {
                    BannerService.ChangeStatusDynamicStaticByParentIds(parentid.ToString());
                }
                else
                {
                    BannerService.ChangeStatusDynamicStaticByBannerIds(id.ToString());
                }
            }
            else
            {
                if (parentid != null)
                {
                    BannerService.ChangeStatusDynamicStaticByParentIds(parentid.ToString());
                }
            }
            ShowMessage("Update status successfully.", "Success");

            return RedirectToAction("Index/" + (Session["id"].ToString().Equals("dynamic") ? 1 : 2), new { page = Session["pageindex"] });
        }
    }
}
